//
//  PhotoTools.swift
//  KeyboardAndEmoji
//
//  Created by AP020Mac mini on 03-08-25.
//

import UIKit
import Photos
import AVFoundation

class PhotoTools: NSObject {
    
    static let shared = PhotoTools()
    private var imagePicker: UIImagePickerController?
    private var resultHandler: ImageBlock?
    
    // MARK: - Authorization
    
    static func requestPhotoAuthorization(handler: @escaping StatusAndDataBlock) {
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                switch status {
                case .authorized, .limited:
                    handler(true, nil)
                case .denied, .restricted:
                    handler(false, AlbumsAuthorizationFailedTip)
                case .notDetermined:
                    break
                @unknown default:
                    //                    handler(false, "未知的相册权限状态")
                    break
                }
            }
        }
    }
    
    static func requestCameraAuthorization(handler: @escaping StatusAndDataBlock) {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                if granted {
                    handler(true, nil)
                } else {
                    handler(false, CameraAuthorizationFailedTip)
                }
            }
        }
    }
    
    // MARK: - Present Picker
    
    func showPhotoAndCameraPicker(in viewController: UIViewController, isPhoto: Bool, resultHandler: @escaping ImageBlock) {
        if isPhoto {
            showPhotoPicker(in: viewController, resultHandler: resultHandler)
        } else {
            showCameraPicker(in: viewController, resultHandler: resultHandler)
        }
    }
    
    func showPhotoPicker(in viewController: UIViewController, resultHandler: @escaping ImageBlock) {
        self.resultHandler = resultHandler
        
        PhotoTools.requestPhotoAuthorization { [weak self] success, message in
            guard let self = self else { return }
            
            if success {
                self.imagePicker = UIImagePickerController()
                self.imagePicker?.delegate = self
                self.imagePicker?.modalPresentationStyle = .fullScreen
                self.imagePicker?.allowsEditing = false
                self.imagePicker?.sourceType = .photoLibrary
                
                if let picker = self.imagePicker {
                    viewController.present(picker, animated: true)
                }
            } else if let messageStr = message as? String {
#warning("去设置相机授权")
                //                WZMDialogTool.showLeftAndRightTitle(withTitle: messageStr,textAlignment: .center , leftTitle: "Cancel", rightTitle: "Go setting", viewTag: 1002, parentView: nil, canTap: false, cancelClick: nil, sureClick: {
                //                    MainTools.openExternalLink(urlString: UIApplication.openSettingsURLString)
                //                })
                
                print("去设置相册授权")
            }
        }
    }
    
    func showCameraPicker(in viewController: UIViewController, resultHandler: @escaping ImageBlock) {
        guard UIImagePickerController.isCameraDeviceAvailable(.rear) else {
            //            MBProgressHUD.showCustomToast(message: NotSupportCameraTip)
            print("去设置相机授权")
            
            return
        }
        self.resultHandler = resultHandler
        PhotoTools.requestCameraAuthorization { [weak self] success, message in
            guard let self = self else { return }
            
            if success {
                self.imagePicker = UIImagePickerController()
                self.imagePicker?.delegate = self
                self.imagePicker?.modalPresentationStyle = .fullScreen
                self.imagePicker?.sourceType = .camera
                self.imagePicker?.allowsEditing = true
                
                if let picker = self.imagePicker {
                    viewController.present(picker, animated: true)
                }
            } else if let messageStr = message as? String {
                print("去设置相机授权")
                
                //                WZMDialogTool.showLeftAndRightTitle(withTitle: messageStr,textAlignment: .center , leftTitle: "Cancel", rightTitle: "Go setting", viewTag: 1002, parentView: nil, canTap: false, cancelClick: nil, sureClick: {
                //                    MainTools.openExternalLink(urlString: UIApplication.openSettingsURLString)
                //                })
            }
        }
    }
    
    
//    static func saveImage(with image: UIImage, completion: @escaping (Bool, Error?) -> Void) {
//        PHPhotoLibrary.shared().performChanges({
//            PHAssetChangeRequest.creationRequestForAsset(from: image)
//        }) { success, error in
//            DispatchQueue.main.async {
//                completion(success, error)
//            }
//        }
//    }
    
    static func saveImage(with image: UIImage, completion: @escaping (Bool, Error?) -> Void) {
        // 转换为PNG数据以保持透明
        guard let pngData = image.pngData() else { return }
        
        // 方法1：使用Photos Framework
        PHPhotoLibrary.shared().performChanges({
            let creationRequest = PHAssetCreationRequest.forAsset()
            creationRequest.addResource(with: .photo, data: pngData, options: nil)
        }) { success, error in
            DispatchQueue.main.async {
                if success {
                    print("透明图片保存成功")
                } else {
                    print("保存失败: \(error?.localizedDescription ?? "未知错误")")
                }
            }
        }
    }
   

    static func saveImage(with image : UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    // MARK: - Save Image
    
    @objc private func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        KLog(error == nil ? "图片保存成功" : "图片保存失败")
    }
}

// MARK: - UIImagePickerControllerDelegate & UINavigationControllerDelegate


extension PhotoTools: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let editedImage = info[.originalImage] as? UIImage {
            if picker.sourceType == .camera {
                UIImageWriteToSavedPhotosAlbum(editedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
            }
            
            picker.dismiss(animated: true) { [weak self] in
                self?.resultHandler?(editedImage.directionCorrection())
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}
